package com.gitee.ywj1352.sharing.db;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置动态 数据源切换
 */
@Configuration
public class DataSourceConfig {

    @Bean("master00")
    @ConfigurationProperties(prefix = "spring.datasource.master00")
    public DataSource master01() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean("master01")
    @ConfigurationProperties(prefix = "spring.datasource.master01")
    public DataSource master02() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean("slave")
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slave() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean("dynamicDataSource")
    @ConditionalOnMissingClass("org.apache.shardingsphere.driver.api.ShardingSphereDataSourceFactory")
    public DataSource dynamicDataSource(@Qualifier("master") DataSource master, @Qualifier("slave") DataSource slave) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map<Object, Object> dataSourceMap = new HashMap<>(2);
        dataSourceMap.put("master", master);
        dataSourceMap.put("slave", slave);
        // 将 master 数据源作为默认指定的数据源
        dynamicDataSource.setDefaultTargetDataSource(master);
        // 将 master 和 slave 数据源作为指定的数据源
        dynamicDataSource.setDataSources(dataSourceMap);
        return dynamicDataSource;
    }

//    @Bean(name = "mybatisMasterSqlSessionFactory")
//    public SqlSessionFactory mybatisMasterSqlSessionFactory(@Qualifier("sharingDataSource") DataSource dataSource) throws Exception {
//        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
//        bean.setDataSource(dataSource);
//        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapper/*.xml"));
//        return bean.getObject();
//    }

//    @Bean(name = "mybatisMasterTransactionManager")
//    public DataSourceTransactionManager mybatisMasterTransactionManager(@Qualifier("sharingDataSource") DataSource dataSource) {
//        return new DataSourceTransactionManager(dataSource);
//    }

}
